package com.xiaoze.steampy.controller;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.errorprone.annotations.Var;
import com.xiaoze.steampy.common.lang.Result;
import com.xiaoze.steampy.entity.Buyorsell;
import com.xiaoze.steampy.entity.Game;
import com.xiaoze.steampy.entity.User;
import com.xiaoze.steampy.entity.UserGame;
import com.xiaoze.steampy.service.BuyorsellService;
import com.xiaoze.steampy.service.GameService;
import com.xiaoze.steampy.service.UserGameService;
import com.xiaoze.steampy.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author 小泽
 * @create 2022-04-04  12:48
 * 记得每天敲代码哦
 */
@RestController
public class BuyController {

    @Autowired
    private GameService gameService;

    @Autowired
    private UserService userService;

    @Autowired
    private BuyorsellService buyorsellService;

    @RequestMapping("/buy")
    public Result buyGame(@RequestParam("id") Integer id,
                          @RequestParam("gameId") Integer gameId,
                          @RequestParam("sell") Integer sell){

        //拿到卖家得信息，方便增加余额
        User user1 = userService.getOne(new QueryWrapper<User>().eq("username", String.valueOf(sell)));
        System.out.println(id+"   "+gameId+"  "+sell);
        //1:首先根据用户id先拿到用户得用户名和余额
        User user = userService.getById(id);
        // System.out.println(user);
        String username = user.getUsername();
        //再这里呢需要将余额数据类型转换（String 转换成Double）
        Double balance = Double.valueOf(user.getBalance());
        //2:根据gameId拿到游戏得最低价格，
        Game game = gameService.getById(gameId);
        Double lastprice = Double.valueOf(game.getLastprice());
        //经过计算得到最终得余额
        Double finalprice = balance - lastprice;
        Double sellprice = Double.valueOf(user1.getBalance())+lastprice;
        user1.setBalance(String.valueOf(sellprice));


        //将最终余额存入数据库中(记得将Double转换成String)
        user.setBalance(String.valueOf(finalprice));
        userService.saveOrUpdate(user);
        userService.saveOrUpdate(user1);
        //修改BuyOrSell表中得信息
        Buyorsell buyorsell = new Buyorsell();
        buyorsell.setGameId(gameId);
        buyorsell.setSell(Integer.parseInt(username));
        buyorsellService.save(buyorsell);

        //3：根据游戏id删除卖家得信息
        buyorsellService.getOne(gameId, sell);
        return Result.succ("购买成功！");
    }


}
